/**
 * 
 */
package edu.umd.clip.lm.playground;

import java.io.*;
import java.util.*;
import java.util.Map.Entry;

import edu.berkeley.nlp.util.MutableDouble;
import edu.umd.clip.lm.util.*;

/**
 * @author Denis Filimonov <den@cs.umd.edu>
 *
 */
public class PrimitiveMapTest {

	private static final int seed = 1234;
	private static void speedTest(int size, int times) {
		Random rnd = new Random(seed);
		
		Long2DoubleMap map = new Long2DoubleMap(size);
		for(int time=0; time<times; ++time) {
			for(int i=0; i<size; ++i) {
				long key = rnd.nextLong() % size;
				map.addAndGet(key, i);
			}
			double sum = 0;
			
			for(Long2DoubleMap.Iterator iter = map.iterator(); iter.hasNext();) {
				Long2DoubleMap.Entry entry = iter.next();
				entry.setValue(entry.getValue() * 2.0);
				sum += entry.getValue();
			}
			System.out.println(sum);
			map.clear();
		}
	}
	
	private static void speedTestStd(int size, int times) {
		HashMap<Long,MutableDouble> map = new HashMap<Long,MutableDouble>(size);
		Random rnd = new Random(seed);
		for(int time=0; time<times; ++time) {
			for(int i=0; i<size; ++i) {
				long key = rnd.nextLong() % size;
				MutableDouble d = map.get(key);
				if (d == null) {
					d = new MutableDouble(i);
					map.put(key, d);
				} else {
					d.add(i);
				}
			}
			
			double sum = 0;
			for(Iterator<Entry<Long,MutableDouble>> iter = map.entrySet().iterator(); iter.hasNext();) {
				Entry<Long,MutableDouble> entry = iter.next();
				entry.getValue().set(entry.getValue().longValue() * 2.0);
				sum += entry.getValue().doubleValue();
			}
			System.out.println(sum);
			map.clear();
		}
	}
	
	public static void main(String[] args) throws Exception {
		//BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		//in.readLine();
		long start = System.currentTimeMillis();
		if (args.length > 0) {
			System.out.println("custom maps");
			speedTest(6000000,3);
		} else {
			System.out.println("standard maps");
			speedTestStd(6000000,3);
		}
		long end = System.currentTimeMillis();
		System.out.println((end - start) * 0.001);
		return;
		/*
		Long2IntMap map = new Long2IntMap();
		
		int num = 20;
		
		for(int i=0; i<num; ++i) {
			long key = (long)(Math.random() * 100000);
			int value = i;
			
			System.out.printf("inserting %d -> %d\n", key, value);
			map.put(key, value);
		}
		System.out.println();
		Long2IntMap.Iterator iterator = map.iterator();
		for(; iterator.hasNext();) {
			iterator.next();
			System.out.printf("iterating: %d -> %d\n", iterator.getKey(), iterator.getValue());
		}
		*/
	}
}
